/**
 * Copyright 2014 wasu.com
 *
 *
 * Create on 2015-3-18 下午7:34:24
 */
package xiaojian.toolkit.ebus.unit;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher;

import com.google.common.base.Preconditions;

/**
 * @author <a href="mailto:caoxiaojian@wasu.com>xiaojian.cao</a>
 * 
 */
public class ZKUtils {

	static String ZNODE_PATH_DELIMITER = "/";

	/**
	 * 组装zk的node 路径。[p1, p2, p3, path] 返回/cfg/p1/p2/p3
	 * 
	 * @param args
	 * @return
	 */
	public static String makeZNodePath(String... args) {
		Preconditions.checkArgument(args.length >= 1);

		StringBuffer sb = new StringBuffer();
		for (String str : args) {
			sb.append(ZNODE_PATH_DELIMITER).append(str);
		}

		return sb.toString();
	}

	public static List<String> getZnodeChilden(CuratorFramework zk, String zNode)
			throws Exception {
		Preconditions.checkArgument(StringUtils.isNoneEmpty(zNode));
		Preconditions.checkArgument(zk != null);

		return zk.getChildren().forPath(zNode);
	}

	/**
	 * 检查节点是否存在。
	 * 
	 * @param zk
	 * @param zNode
	 * @return true - 节点存在； false - 节点不存在。
	 */
	public static boolean checkNodeExist(CuratorFramework zk, String zNode)
			throws Exception {
		Preconditions.checkArgument(zk != null);
		Preconditions.checkArgument(StringUtils.isNoneEmpty(zNode));

		return zk.checkExists().forPath(zNode) != null;
	}

	/**
	 * 使用exist方式去给某个节点绑定个监听器。
	 * 
	 * @param zk
	 * @param zNode
	 * @param watcher
	 * @throws InterruptedException
	 * @throws KeeperException
	 */
	public static void registerWatcher(CuratorFramework zk, String zNode,
			Watcher watcher) throws KeeperException, InterruptedException {
		Preconditions.checkArgument(zk != null);
		Preconditions.checkArgument(StringUtils.isNoneEmpty(zNode));
		Preconditions.checkArgument(watcher != null);

		zk.getChildren().usingWatcher(watcher);
	}

	/**
	 * 得到节点的数值。
	 * 
	 * @param zk
	 * @param nodePath
	 * @return
	 * @throws Exception
	 */
	public static String getValue(CuratorFramework zk, String nodePath)
			throws Exception {
		Preconditions.checkArgument(zk != null);
		Preconditions.checkArgument(StringUtils.isNotEmpty(nodePath));

		return new String(zk.getData().forPath(nodePath));
	}

}
